<template>
    <div class="container">
        <div class="MessageWindow">
            <ul>
                <!-- <li v-for="{info: item} in displayData.data">{{ item }}</li> -->
                 <a @click="PreviousPage" v-if="page != 0" class="pagebutton">Previous</a>
                <div class="messageContainer" v-for="item in displayData.data">
                    <span class="dataItem">{{ item[1] }}</span>
                    <button @click="deleteMessage(item[0])">x</button>
                </div>
                <a class="pagebutton" @click="NextPage" v-if="page * 20 + 20 <= displayData.count">Next</a>
            </ul>
        </div>
        <div class="InputWindow">
            <textarea type="text" @keydown.enter="sendMessage($event)" v-model="inputValue"></textarea>
        </div>
    </div>

</template>

<script setup lang="ts" name="WebNotes">
    import {ref, onBeforeMount, reactive, onMounted, onUnmounted} from "vue"
    import axios from "axios"
    
    let inputValue = ref()
    let page = 0
    let eventSource: any
    let ip = 'http://localhost:5000/api/'
    let displayData = reactive({
        count: 0,
        data: [] as any
    })


    //load database data before mount
    onBeforeMount(getDisplayData)
    onMounted(()=> {
        eventSource = new EventSource(ip + 'events')
        eventSource.onmessage = (event:any) => {
            let data = event.data
            if (data == 'freshInfo') {
                getDisplayData()
            }
        }
        eventSource.onerror = (error:any) => {
            console.error('EventSource failed:', error)
        }
    })

    onUnmounted(() => {
        if (eventSource) {
            eventSource.close()
        }
    })

    async function getData() {
        try {
            const result = await axios.post(ip + 'getdata', {
                page: page
            })
            return JSON.stringify(result.data)
        }catch (err) {
            alert(err)
        }
        return ""
    }

    async function getDisplayData() {
        let tempData = await getData()
        let jsonData = JSON.parse(tempData)
        displayData.count = jsonData.total
        displayData.data = jsonData.msg
    }

    async function sendMessage(event:any) {
        event.preventDefault()
        if (!inputValue.value) {
            alert('The content cannot be empty!')
            return
        }
        let workValue = inputValue.value
        //clear the value of inputValue
        inputValue.value = ''
        //Add message in display window before send to server which can show faster
        //Using a fake id during waiting the true id from server
        let newMsg = {
            0: -1,
            1: workValue
        }
        displayData.data.unshift(newMsg)
        try {
            const result = await axios.post(ip + 'upload', {
                msg: workValue
            })
        }catch (err) {
            alert(err)
        }
        //refresh the data, needing reset the page and get data by post api
        page = 0
        getDisplayData()
    }

    async function deleteMessage(id: number) {
        //Firstly delete the message in display window
        for (let i = 0; i < displayData.data.length; ++i) {
            let item = displayData.data[i]
            if (item[0] == id) {
                displayData.data.splice(i, 1)
            }
        }
        try{
            await axios.post(ip + 'deleteOne', {
                id: id
            })
        }catch(err) {
            alert(err)
        }
    }

    function PreviousPage() {
        if (page > 0) {
            page -= 1
            getDisplayData()
        }
    }

    function NextPage() {
        if (page * 20 + 20 <= displayData.count) {
            page += 1
            getDisplayData()
        }
    }

</script>

<style scoped>
    textarea{
        resize: none;
        font-size: 20px;
        width: 100%;
        height: 100%;
    }
    li{
        list-style-type: none;
    }
    .container{
        width: 600px;
        height: 800px;
        border: solid 2px green;
        margin: 0 auto;
        overflow: hidden;
        border-radius: 2%;
    }
    .MessageWindow{
        width: 600px;
        height: 600px;
        overflow-y: scroll;
    }
    .InputWindow{
        width: 100%;
        height: 100%;
        background-color: gainsboro;
        border-radius: 2%;
    }
    .messageContainer{
        display: flex;
        justify-content: flex-end;
        margin-right: 5%;
        margin-top: 10px;
        border-radius: 2%;
    }
    .dataItem{
        background-color: greenyellow;
        font-size: 20px;
        cursor: default;  
        border-radius: 20%;
    }
    .dataItem + button{
        visibility: hidden;
    }
    .dataItem + button:hover{
        visibility: visible;
        background-color: pink;
        border-radius: 20%;
        cursor: pointer;
    }
    /* when the cursor hover on the span, button display, else hidden */
    .dataItem:hover + button{
        visibility: visible;
        background-color: pink;
        display: block;
        border-radius: 20%;
    }
    .pagebutton{
        width: 50px;
        cursor: pointer;
        display: block;
        margin: 1% auto;
        color: rgb(101, 221, 129);
    }
</style>